package com.nutrition.health.controller;

import com.nutrition.health.model.UserHealthProfile;
import com.nutrition.health.service.UserHealthProfileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users/{userId}/health-profile")
@Api(tags = "用户健康档案", description = "用户健康档案和个性化健康建议相关操作")
@CrossOrigin(origins = "*")
public class UserHealthProfileController {

    private final UserHealthProfileService profileService;

    @Autowired
    public UserHealthProfileController(UserHealthProfileService profileService) {
        this.profileService = profileService;
    }

    @GetMapping
    @ApiOperation("获取用户健康档案")
    public ResponseEntity<UserHealthProfile> getUserHealthProfile(@PathVariable Long userId) {
        return profileService.getProfileByUserId(userId)
                .map(profile -> new ResponseEntity<>(profile, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @PostMapping
    @ApiOperation("创建用户健康档案")
    public ResponseEntity<UserHealthProfile> createUserHealthProfile(
            @PathVariable Long userId,
            @Valid @RequestBody UserHealthProfile profile) {

        try {
            System.out.println("接收到创建健康档案请求，userId: " + userId);
            System.out.println("健康档案数据: " + profile);

            UserHealthProfile createdProfile = profileService.createProfile(userId, profile);
            System.out.println("健康档案创建成功，ID: " + createdProfile.getId());

            return new ResponseEntity<>(createdProfile, HttpStatus.CREATED);
        } catch (Exception e) {
            System.err.println("创建健康档案时发生错误: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    @PutMapping
    @ApiOperation("更新用户健康档案")
    public ResponseEntity<UserHealthProfile> updateUserHealthProfile(
            @PathVariable Long userId,
            @Valid @RequestBody UserHealthProfile profileDetails) {

        UserHealthProfile updatedProfile = profileService.updateProfile(userId, profileDetails);
        return new ResponseEntity<>(updatedProfile, HttpStatus.OK);
    }

    @DeleteMapping
    @ApiOperation("删除用户健康档案")
    public ResponseEntity<Void> deleteUserHealthProfile(@PathVariable Long userId) {
        profileService.deleteProfile(userId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @GetMapping("/bmr")
    @ApiOperation("计算用户的基础代谢率")
    public ResponseEntity<Map<String, Double>> calculateBMR(@PathVariable Long userId) {
        double bmr = profileService.calculateBMR(userId);
        Map<String, Double> bmrMap = new HashMap<>();
        bmrMap.put("bmr", bmr);
        return new ResponseEntity<>(bmrMap, HttpStatus.OK);
    }

    @GetMapping("/daily-calorie-needs")
    @ApiOperation("计算用户的每日卡路里需求")
    public ResponseEntity<Map<String, Double>> calculateDailyCalorieNeeds(@PathVariable Long userId) {
        double calorieNeeds = profileService.calculateDailyCalorieNeeds(userId);
        Map<String, Double> calorieNeedsMap = new HashMap<>();
        calorieNeedsMap.put("calorieNeeds", calorieNeeds);
        return new ResponseEntity<>(calorieNeedsMap, HttpStatus.OK);
    }

    @GetMapping("/bmi")
    @ApiOperation("计算用户的BMI指数")
    public ResponseEntity<Map<String, Object>> calculateBMI(@PathVariable Long userId) {
        double bmi = profileService.calculateBMI(userId);
        String category = profileService.getBMICategory(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("bmi", bmi);
        map.put("category", category);
        return new ResponseEntity<>(
                map,
                HttpStatus.OK);
    }

    @GetMapping("/nutrient-requirements")
    @ApiOperation("获取用户的营养素需求")
    public ResponseEntity<Map<String, Double>> getNutrientRequirements(@PathVariable Long userId) {
        Map<String, Double> requirements = profileService.generateNutrientRequirements(userId);
        return new ResponseEntity<>(requirements, HttpStatus.OK);
    }

    @GetMapping("/health-recommendations")
    @ApiOperation("获取个性化健康建议")
    public ResponseEntity<Map<String, String>> getHealthRecommendations(@PathVariable Long userId) {
        Map<String, String> recommendations = profileService.generateHealthRecommendations(userId);
        return new ResponseEntity<>(recommendations, HttpStatus.OK);
    }

    @GetMapping("/diet-plan")
    @ApiOperation("获取个性化饮食计划")
    public ResponseEntity<Map<String, Object>> getDietPlan(@PathVariable Long userId) {
        Map<String, Object> dietPlan = profileService.generateDietPlan(userId);
        return new ResponseEntity<>(dietPlan, HttpStatus.OK);
    }

    @GetMapping("/test-endpoint")
    @ApiOperation("测试端点")
    public ResponseEntity<Map<String, Object>> test(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        response.put("message", "测试成功");
        response.put("userId", userId);
        response.put("timestamp", new Date().toString());
        return new ResponseEntity<>(response, HttpStatus.OK);
    }
}